package com.tianpengtech.front.web.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.util.IpKit;
import com.tianpengtech.front.web.login.LoginService;

/**
 * Account login intercept
 * @author Delicate
 */
public class PassportInterceptor implements Interceptor {
    public void intercept(Invocation inv) {
        User loginUser = null;
        Controller c = inv.getController();
        String sessionId = c.getCookie(LoginService.sessionIdName);
        if (sessionId != null) {
            loginUser = LoginService.me.getLoginAccountWithSessionId(sessionId);
            if (loginUser == null) {
                String loginIp = IpKit.getRealIp(c.getRequest());
                loginUser = LoginService.me.loginWithSessionId(sessionId, loginIp);
            }
            if (loginUser != null) {
                // 用户登录账号
                c.setAttr(LoginService.loginAccountCacheName, loginUser);
                inv.invoke();
            } else {
                c.removeCookie(LoginService.sessionIdName); // cookie 登录未成功，证明该 cookie 已经没有用处，删之
                String queryString = inv.getController().getRequest().getQueryString();
                if (StrKit.isBlank(queryString)) {
                    inv.getController().redirect("/index?returnUrl=" + inv.getActionKey());
                } else {
                    inv.getController().redirect("/index?returnUrl=" + inv.getActionKey() + "?" + queryString);
                }
            }
        }else{
            c.removeCookie(LoginService.sessionIdName); // cookie 登录未成功，证明该 cookie 已经没有用处，删之
            String queryString = inv.getController().getRequest().getQueryString();
            if (StrKit.isBlank(queryString)) {
                inv.getController().redirect("/index?returnUrl=" + inv.getActionKey());
            } else {
                inv.getController().redirect("/index?returnUrl=" + inv.getActionKey() + "?" + queryString);
            }
        }
    }
}
